package com.cqc.manage.service.Imp;

import com.cqc.manage.entity.Role;
import com.cqc.manage.error.ErrorEnum;
import com.cqc.manage.repositories.RoleRepositories;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/** 角色服务类 */
@Service
public class RoleService {

    private static Logger LOG = LoggerFactory.getLogger(RoleService.class);

    @Autowired
    private RoleRepositories roleRepositories;

    /**
     * 添加角色
     *
     * @param role
     */
    public Role addRole(Role role) {
        LOG.debug("添加用户，参数:{}", role);
        //     数据校验
        checkUser(role);
        //     设置默认值
        setDefault(role);
        Role save = roleRepositories.save(role);
        LOG.debug("添加用户结果{}", save);
        return save;
    }

    /**
     * 更新角色
     *
     * @return
     */
    public Role updateRole(String roleId,String roleName) {
        Role role = new Role();
        role.setRoleId(roleId);
        role.setRoleName(roleName);
        role.setCreateAt(new Date());
        LOG.debug("更新角色：{}", role);
        Role save = roleRepositories.save(role);
        return save;
    }

    /**
     * 通过角色id查询角色
     *
     * @param id
     * @return
     */
    public Role selectById(String id) {
        Role roleByRoleId = roleRepositories.findRoleByRoleId(id);
        return roleByRoleId;
    }
    /**
     * 通过角色名称查询角色
     *
     * @param roleName
     * @return
     */
    public Role selectByName(String roleName) {
        Role roleByRoleName = roleRepositories.findRoleByRoleName(roleName);
        return roleByRoleName;
    }

    /**
     * 获取全部的角色
     *
     * @return
     */
    public List<Role> getAllRole() {
        List<Role> allRole = roleRepositories.findAll();
        return allRole;
    }

    /**
     * 设置随机ID
     *
     * @param role
     */
    private void setDefault(Role role) {
        role.setRoleId(UUID.randomUUID().toString().replace("-", ""));
        role.setCreateAt(new Date());
    }

    /**
     * 数据校验
     *
     * @param role
     */
    private void checkUser(Role role) {
        Assert.notNull(role.getRoleName(), ErrorEnum.LACK_USER_USERNAME.getCode());
        Assert.isNull(roleRepositories.findRoleByRoleName(role.getRoleName()),ErrorEnum.ROLE_NAME_EXIST.getCode());

    }
}
